package com.tdwyz.fictionmanage.controller;

import com.tdwyz.fictionmanage.enums.FileType;
import com.tdwyz.fictionmanage.enums.ImgType;
import com.tdwyz.fictionmanage.pojo.FileUpload;
import com.tdwyz.fictionmanage.pojo.Result;
import com.tdwyz.fictionmanage.service.FileUploadService;
import com.tdwyz.fictionmanage.utils.AliOssUtil;
import com.tdwyz.fictionmanage.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author 14543
 * @version 1.0
 * @description: TODO
 * @date 2024/7/28 10:26
 */
@RestController
@RequestMapping("/upload")
public class FileUploadController {


    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 文件上传
     * @param file
     * @param fileType
     * @return
     * @throws Exception
     */
    @PostMapping
    public Result upload(MultipartFile file, @RequestParam Integer fileType) throws Exception {
        //1.获取文件名
        String originalFilename = file.getOriginalFilename();
        //2.获取文件用途
        if(!FileType.contains(fileType)){
            return Result.defeat("文件用途错误");
        }
        //3.文件类型后戳 判断
        String postType = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(postType == null){
            return Result.defeat("文件类型获取失败");
        }
        if(!ImgType.contains(postType)){
            return Result.defeat("文件类型不支持");
        }
        //4.上传文件 产生随机的文件名保证不重复 保留原有的文件格式后缀
        originalFilename = UUID.randomUUID().toString()+postType;
        String url = AliOssUtil.uploadFile(originalFilename, file.getInputStream());
        //5.保存文件地址
        FileUpload fileUpload = new FileUpload(
                originalFilename,
                url,
                fileType,
                ThreadLocalUtil.getUserId()
        );
        //将文件上传到文件表
        fileUploadService.add(fileUpload);
        return Result.success(url);
    }
}
